package struts3.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts3.form.ActionForm;
import struts3.form.XmlBean;
import struts3.util.FullBean;

public class ActionServlet extends HttpServlet {


	private static final long serialVersionUID = -2687701955014742725L;
	
	public ActionServlet(){}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			
		String path = this.getPath(req.getServletPath());
		Map<String,XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("struts");
		XmlBean xml = map.get(path);
		String beanClass = xml.getBeanClass();
		ActionForm form = FullBean.getBean(beanClass, req);
		String actionType = xml.getActionClass();
		System.out.println(xml.getActionForward());
		Action action = null;
		String url = "";
		
		try{
			Class clazz = Class.forName(actionType);
			action = (Action) clazz.newInstance();
			url = action.execute(req, form, xml.getActionForward());
			
		}catch (Exception e) {
			e.printStackTrace();
			System.out.println("严重：控制器异常！！！！");
		}
		System.out.println(url);
		RequestDispatcher rd = req.getRequestDispatcher(url);
		rd.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		this.doGet(req, resp);
	}
	
	private String getPath(String servletPath){
		return servletPath.split("\\.")[0];
	}
}
